package org.example.dto;

import lombok.Data;
import org.example.dao.entity.Users;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
public class DetailDTO {
    private String field;
    private String oldValue;
    private String newValue;


    public static List<DetailDTO> getDifference(Users oldUser, Users newUser) {
        List<DetailDTO> changes = new ArrayList<>();
        try {
            Field[] fields = Users.class.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object oldValue = field.get(oldUser);
                Object newValue = field.get(newUser);

                // 如果值不一样，记录变化（排除一些不需要记录的字段）
                if (oldValue == null && newValue == null) continue;
                if (oldValue != null && oldValue.equals(newValue)) continue;

                // 你可以扩展一个字段忽略列表，比如 "updateTime" 之类的
                String fieldName = field.getName();
                if ("gmtCreate".equals(fieldName) || "password".equals(fieldName)) continue;

                DetailDTO detailDTO = new DetailDTO();
                detailDTO.setField(fieldName);
                detailDTO.setOldValue(oldValue == null ? "" : oldValue.toString());
                detailDTO.setNewValue(newValue == null ? "" : newValue.toString());
                changes.add(detailDTO);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("字段差异比对失败", e);
        }
        return changes;
    }


}
